"""
    Author:
    Date: 2019-01-17

    辅助函数。
"""

from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.shortcuts import render
from functools import wraps

SESSION_KEY_FOR_LOGIN = '_guild_mobile'


def login(request, mobile):
    """ 登录 """
    request.session[SESSION_KEY_FOR_LOGIN] = mobile


def logout(request):
    """ 登出 """
    del request.session[SESSION_KEY_FOR_LOGIN]


def guild_login_required(view_func):
    """ 检测用户是否使用登录 """
    @wraps(view_func)
    def new_view_func(request, *args, **kwargs):
        mobile = request.session.get(SESSION_KEY_FOR_LOGIN, None)
        if mobile is None and not settings.DEBUG:
            raise PermissionDenied

        # Return the HttpResponse object
        response = view_func(request, *args, **kwargs)
        return response

    return new_view_func


def get_request_mobile(request):
    """ 获取request对应的partner id """
    mobile = request.session.get(SESSION_KEY_FOR_LOGIN, None)
    return mobile


def build_context(request):
    """ 构造上下文信息 """
    if not request:
        return {}

    context = {
        'user': request.user,
    }
    return context


def show_page_500(request, data):
    """ 显示500页面 """
    if type(data) == dict:
        message_id = data['id']
        message = data['message']
        message = f'[{message_id}] {message}'
    else:
        message = data
    return render(request, 'guild/500.html', {'message': message})


def show_page_tips(request, data):
    """ 显示提示页面 """
    if type(data) == dict:
        message_id = data['id']
        message = data['message']
        message = f'[{message_id}] {message}'
    else:
        message = data
    return render(request, 'guild/tips.html', {'message': message})


def show_success_page(request, message, redirect_url=''):
    """ 显示成功页面 """
    context = {
        'message': message,
        'redirect_url': redirect_url,
    }
    return render(request, 'guild/success.html', context)


def show_warn_page(request, message, redirect_url=''):
    """ 显示警告页面 """
    context = {
        'message': message,
        'redirect_url': redirect_url,
    }
    return render(request, 'guild/warn.html', context)


if __name__ == '__main__':
    print('ok')
